<?php

	class source
	{

		var $fw		= null;
		var $sec	= null;

		function source(&$framework, &$security)
		{

			$this->fw	= &$framework;
			$this->sec	= &$security;

			$this->fw->pc_item('My Collection', 'Items in your collection', 'index.php?what=mymovies');

			switch($this->fw->do)
			{

				// Borrowing
				case 'borrow':
					$this->borrow_movies();
					break;

				case 'borrow_process':
					$this->process_borrow_movies();
					break;

				case 'borrowed':
					$this->list_borrowed_movies();
					break;

				case 'borrow_requests':
					$this->list_borrow_requests();
					break;

				// Email Collection
				case 'email':
					$this->email_list_form();
					break;

				case 'process_email':
					$this->process_email_list_form();
					break;

				// Other
				case 'process':
					$this->process_movies();
					break;

				case 'edit':
					$this->edit_movies();
					break;

				case 'add':
					$this->add_movies();
					break;

				case 'remove':
					$this->remove_movies();
					break;

				default:
					$this->list_movies();
					break;

			}

		}

		// display a list of movies that people wish to borrow of the current member
		function list_borrow_requests()
		{

			$this->fw->pc_item('Borrow Requests', 'A list of your movies that other members would currently like to borrow', 'index.php?what=mymovies&do=borrow_requests');

			$member_id	= $this->sec->dtls['id'];

			$this->fw->template	= 'mymovies.borrow_requests.tpl';

			$this->fw->content['movies']	= $this->fw->get_request_borrow($member_id);

		}

		function list_borrowed_movies()
		{

			$this->fw->pc_item('Lent Out Movies', 'A list of your movies from your collection that are currently borrowed by other members/outsiders', 'index.php?what=mymovies');

			$member_id	= (int)$this->sec->dtls['id'];

			$this->fw->template	= 'mymovies.borrowed.tpl';

			$this->fw->content['borrowed']	= $this->fw->get_borrowed($member_id);

		}

		function process_borrow_movies()
		{

			// get our details!
			$id				= $_POST['id'];
			$borrower_id	= (int)@$_POST['borrower_id'];
			$contact_name	= trim($_POST['contact_name']);
			$contact_email	= trim($_POST['contact_email']);

			$mode	= 'id';

			// Error Checking
			$err	= array();

			// no borrower information provided
			if($borrower_id == 0 && empty($contact_name) && empty($contact_email))
			{

				$err['borrower_id']	= 'No borrower information provided';

			}

			if($borrower_id == 0)
			{

				$mode	= 'contact';

				if(empty($contact_name))
				{

					$err['contact_name']	= 'Required Field';

				}

				if(empty($contact_email))
				{

					$err['contact_email']	= 'Required Field';

				}
				elseif(!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $contact_email))
				{

					$err['contact_email']	= 'Valid Email Address Required';

				}

			}

			if(count($err) == 0)
			{

				if($mode == 'id')
				{

					$contact_name	= 'NULL';
					$contact_email	= 'NULL';

					$member_dtls	= $this->fw->get_member_details($borrower_id);
					$username		= $member_dtls['username'];

				}
				else
				{

					$borrower_id	= 'NULL';

					$username		= ucwords($contact_name);

					$contact_name	= '\''. addslashes($contact_name) .'\'';
					$contact_email	= '\''. addslashes($contact_email) .'\'';

				}

				$count	= 0;

				// Lets loop though these movies and add the relavant details
				$member_id	= (int)$this->sec->dtls['id'];
				foreach($id as $v)
				{

					$own_id	= $this->fw->movie_own($v, $member_id, true);

					// add an entry into the borrow table
					$sql	= $this->fw->_pq("INSERT INTO #__borrow (movie_id, own_id, owner_id, borrower_id, borrow_status, borrow_request_date, borrow_borrowed_date, borrow_contact_name, borrow_contact_email) VALUES (%s, %s, %s, %s, 'borrowed', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), $contact_name, $contact_email)", (int)$v, $own_id, $member_id, $borrower_id);
					$result	= mysql_query($sql) or die(mysql_error());

					if($result)
					{

						$count++;

					}

				}

				$_SESSION['msg']	= $count .' Movies Successfully lent to '. $username;
				header('location: index.php?what=mymovies');
				exit;

			}
			else
			{

				$this->fw->do	= 'borrow';
				$this->borrow_movies('Errors Found', $err);

			}

		}

		function borrow_movies()
		{

			$id				= $_REQUEST['id'];
			$id				= is_array($id) ? $id : array($id);
			$borrower_id	= (int)@$_REQUEST['member_id'];

			$ids		= array();

			$member_id	= $this->sec->dtls['id'];

			foreach($id as $i)
			{

				// --= Ensure that this movie id belongs to the members collection!
				if($this->fw->movie_own($i, $member_id))
				{

					$ids[]	= (int)$i;

				}

			}

			if(count($id) > 0 && ($this->fw->do == 'borrow_process' || $borrower_id > 0))
			{
			}
			else
			{

				// No details about who is borrowing the selected movies has been entered
				$ids	= implode(',', $ids);

				$sql	= $this->fw->_pq("SELECT movie_id, movie_title, movie_imdb, movie_year FROM #__movies WHERE movie_id IN ($ids) ORDER BY movie_title ASC");
				$result	= mysql_query($sql) or die(mysql_error());

				while($row = mysql_fetch_array($result))
				{

					$results[]	= array('id'		=> $row['movie_id'],
										'title'		=> $row['movie_title'],
										'imdb'		=> $row['movie_imdb'],
										'imdb_url'	=> $this->fw->imdb_url($row['movie_imdb']),
										'year'		=> $row['movie_year']);

				}

				$this->fw->template	= 'mymovies.borrow.tpl';

				$this->fw->content['movies']	= isset($results) ? $results : false;
				$this->fw->content['members']	= $this->fw->_convert_array($this->fw->get_members(1, 1, false), 'id', 'username');

			}

		}

		function email_list_form()
		{

			if($this->fw->do == 'process_email')
			{
			}

			$this->fw->pc_item('Email Movie Collection', 'Email your collection (or parts of it) to specified email addresses', 'index.php?what=mymovies&do=email');

			$this->fw->template = 'mymovies.email_form.tpl';

			// Set form data
			$genres	= $this->fw->get_genres();
			$tmp	= array();
			$sel	= array();

			foreach($genres as $v)
			{

				$tmp[$v['id']] = $v['name'];
				$sel[] = $v['id'];

			}

			$this->fw->content['src_genre']		= $tmp;
			$this->fw->content['src_genre_sel']	= $sel;
			unset($tmp, $sel);

			// Form values

		}

		function list_movies($msg = null)
		{

			$this->fw->pc_item('List', 'Movies in your collection database', 'index.php?what=mymovies');

			$member_id	= $this->sec->dtls['id'];

			$this->fw->template	= 'mymovies.list.tpl';

			$filter	= trim(@$_REQUEST['filter']);
			$genre	= trim(@$_REQUEST['genre']);
			$search	= trim(@$_REQUEST['search']);

			// paginiation
			$num	= $this->fw->get_count_movies_in_member($member_id, $filter, $search, $genre);;
			$pagin	= $this->fw->pagination($num);

			$this->fw->content['movies']		= $this->fw->get_member_movies($member_id, $filter, $search, $genre, $pagin);
			$this->fw->content['pagination']	= $pagin;
			$this->fw->content['filter']		= $filter;
			$this->fw->content['genre']			= $genre;
			$this->fw->content['search']		= htmlentities($search);

			$this->fw->content['member']	= $this->fw->get_member_details($member_id);

		}

		function add_movies()
		{

			$this->fw->pc_item('Add Movies', 'Add the selected movies into your collection');

			$id	= isset($_SESSION['id']) ? $_SESSION['id'] : @$_REQUEST['id'];
			unset($_SESSION['id']);
			$id	= is_array($id) ? $id : array($id);

			// validate the provided ids
			foreach($id as $k=>$tmp) {
				if(!is_numeric($tmp)) {
					unset($id[$k]);
				}
			}

			if(count($id) == 0) {
				// no valid id's provided
				$_SESSION['msg'] = 'No movies selected';
				header('location: index.php?what=mymovies');
				exit;
			}

			$member_id	= $this->sec->dtls['id'];
			$movies		= array();

			$this->fw->template	= 'mymovies.form.tpl';
			$this->fw->js[]		= 'mymovies.add.js';

			$sql	= $this->fw->_pq("SELECT movie_id, movie_title, movie_year FROM #__movies WHERE movie_id IN (%s)", implode(',', $id));
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) > 0)
			{

				while($row = mysql_fetch_array($result))
				{

					$movies[$row['movie_id']]	= $row['movie_title'] .' ('. $row['movie_year'] .')';
					$mdata[$row['movie_id']]	= array('medium' => null, 'format' => null, 'ratio' => null, 'language' => null, 'subtitle' => null, 'sound' => null, 'rating' => 0, 'comments' => null);

				}

				$this->fw->content['movies']	= $movies;
				$this->fw->content['mdata']		= $mdata;

			}

			// Assign form data
			$this->fw->content['title']		= 'Add movie(s) to your collection';
			$this->fw->content['action']	= 'add';

			$this->fw->content['medium']	= array_map('trim', explode("\n", $this->fw->config['movie_medium']));
			$this->fw->content['format']	= array_map('trim', explode("\n", $this->fw->config['movie_format']));
			$this->fw->content['ratio']		= array_map('trim', explode("\n", $this->fw->config['movie_ratio']));
			$this->fw->content['language']	= array_map('trim', explode("\n", $this->fw->config['movie_language']));
			$this->fw->content['subtitle']	= array_map('trim', explode("\n", $this->fw->config['movie_subtitle']));
			$this->fw->content['sound']		= array_map('trim', explode("\n", $this->fw->config['movie_sound']));

		}

		function process_movies()
		{

			$id			= $_POST['id'];
			$member_id	= (int)$this->sec->dtls['id'];
			$action		= $_POST['action'];

			if(isset($_POST['ignore']) && $_POST['ignore'] == '1' && $action == 'add')
			{

				// Ignore the 'details' of the selected movies and just add them, flag the movies to be updated at a later date
				$i = 0;

				foreach($id as $v)
				{

					// Lets check if this movie already exists in db
					$sql	= $this->fw->_pq("SELECT COUNT(member_id) FROM #__own WHERE movie_id = '%s' AND member_id = '%s'", $v, $member_id);
					$result	= mysql_query($sql) or die(mysql_error());

					if($result && mysql_result($result, 0, 0) == 0)
					{

						$sql	= $this->fw->_pq("INSERT INTO #__own (member_id, movie_id, own_created, own_updated, own_incomplete) VALUES ('$member_id', '$v', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 1);");
						$result	= mysql_query($sql) or die(mysql_error());

						if($result) $i++;

						// Remove this movie from their wishlist if it exists
						$sql	= $this->fw->_pq("DELETE FROM #__wishlist WHERE member_id = '%s' AND movie_id = '%s'", $member_id, $v);
						$result	= mysql_query($sql) or die(mysql_error());

					}

				}

				$this->fw->update_member_movie_count($member_id);

				$_SESSION['msg'] = $i .' movie(s) added';
				header('location: index.php?what=mymovies');
				exit;

			}
			else
			{

				$own_id		= $_POST['own_id'];
				$medium		= $_POST['medium'];
				$format		= $_POST['format'];
				$ratio		= $_POST['ratio'];
				$language	= $_POST['language'];
				$subtitle	= $_POST['subtitle'];
				$sound		= $_POST['sound'];
				$comment	= $_POST['comment'];
				$rating		= $_POST['rating'];

				// Lets do some checking. All fields apart from comment must have a value.
				$pass		= true;

				if($this->_check_array($medium) == false) $pass = false;
				if($this->_check_array($format) == false) $pass = false;
				if($this->_check_array($ratio) == false) $pass = false;
				if($this->_check_array($language) == false) $pass = false;
				if($this->_check_array($subtitle) == false) $pass = false;
				if($this->_check_array($sound) == false) $pass = false;
				//if($this->_check_array($rating) == false) $pass = false;

				if($pass)
				{

					// Checking completed. All the required values are provided
					$i = 0;

					foreach($id as $v)
					{

						// Lets check if this movie already exists in db
						$sql	= $this->fw->_pq("SELECT COUNT(member_id) FROM #__own WHERE movie_id = '%s' AND member_id = '%s' AND own_id != %s", $v, $member_id, (int)$own_id[$v]);
						$result	= mysql_query($sql) or die(mysql_error());

						if($result && mysql_result($result, 0, 0) == 0)
						{


							$comment[$v]	= str_replace('<br />', "\n", $comment[$v]);
							$rating[$v]		= (int)$rating[$v];

							if($action == 'edit')
							{

								$sql	= $this->fw->_pq("UPDATE #__own SET own_dtls_medium = '%s', own_dtls_format = '%s', own_dtls_ratio = '%s', own_dtls_language = '%s', own_dtls_subtitle = '%s', own_dtls_sound = '%s', own_dtls_comment = '%s', own_rating = %s, own_updated = UNIX_TIMESTAMP(), `own_incomplete` = 0 WHERE own_id = %s AND member_id = %s AND movie_id = %s", $medium[$v], $format[$v], $ratio[$v], $language[$v], $subtitle[$v], $sound[$v], $comment[$v], $rating[$v], $own_id[$v], $member_id, (int)$v);
								$result	= mysql_query($sql) or die(mysql_error());

								if($result) $i++;

							}
							else
							{

								$sql	= $this->fw->_pq("INSERT INTO #__own (member_id, movie_id, own_dtls_medium, own_dtls_format, own_dtls_ratio, own_dtls_language, own_dtls_subtitle, own_dtls_sound, own_dtls_comment, own_rating, own_created, own_updated) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());", $member_id, $v, $medium[$v], $format[$v], $ratio[$v], $language[$v], $subtitle[$v], $sound[$v], $comment[$v], $rating[$v]);
								$result	= mysql_query($sql) or die(mysql_error());

								if($result) $i++;

							}

							// Remove this movie from their wishlist if it exists
							$sql	= $this->fw->_pq("DELETE FROM #__wishlist WHERE member_id = %s AND movie_id = %s", $member_id, (int)$v);
							$result	= mysql_query($sql) or die(mysql_error());

						}

					}

					$this->fw->update_member_movie_count($member_id);

					if($action == 'edit')
					{

						$_SESSION['msg'] = $i .' movie(s) edited';

					}
					else
					{

						$_SESSION['msg'] = $i .' movie(s) added';

					}

					header('location: index.php?what=mymovies');
					exit;

				}
				else
				{

					$this->add_movies();

				}


			}

		}

		function edit_movies()
		{

			$this->fw->pc_item('Edit Movies', 'Edit the details of the movies selected from your collection');

			$id	= isset($_SESSION['id']) ? (int)$_SESSION['id'] : (int)@$_REQUEST['id'];
			unset($_SESSION['id']);

			$member_id	= (int)$this->sec->dtls['id'];

			$this->fw->template	= 'mymovies.form.tpl';
			$this->fw->js[]		= 'mymovies.add.js';

			$sql	= $this->fw->_pq("SELECT own_id, own_dtls_medium, own_dtls_format, own_dtls_ratio, own_dtls_language, own_dtls_subtitle, own_dtls_sound, own_rating, own_dtls_comment, m.movie_id, m.movie_title, m.movie_year FROM #__own o INNER JOIN #__movies m ON o.movie_id = m.movie_id WHERE o.member_id = %s AND o.movie_id = %s", $member_id, $id);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) > 0)
			{

				while($row = mysql_fetch_assoc($result))
				{

					$movies[$row['movie_id']]	= $row['movie_title'] .' ('. $row['movie_year'] .')';
					$mdata[$row['movie_id']]	= array('own_id'	=> $row['own_id'],
														'medium'	=> $row['own_dtls_medium'],
														'format'	=> $row['own_dtls_format'],
														'ratio'		=> $row['own_dtls_ratio'],
														'language'	=> $row['own_dtls_language'],
														'subtitle'	=> $row['own_dtls_subtitle'],
														'sound'		=> $row['own_dtls_sound'],
														'rating'	=> $row['own_rating'],
														'comments'	=> $row['own_dtls_comment']);

				}

				$this->fw->content['movies']	= $movies;
				$this->fw->content['mdata']		= $mdata;

			}

			// Assign form data
			$this->fw->content['title']		= 'Edit Movies';
			$this->fw->content['action']	= 'edit';

			$this->fw->content['medium']	= array_map('trim', explode("\n", $this->fw->config['movie_medium']));
			$this->fw->content['format']	= array_map('trim', explode("\n", $this->fw->config['movie_format']));
			$this->fw->content['ratio']		= array_map('trim', explode("\n", $this->fw->config['movie_ratio']));
			$this->fw->content['language']	= array_map('trim', explode("\n", $this->fw->config['movie_language']));
			$this->fw->content['subtitle']	= array_map('trim', explode("\n", $this->fw->config['movie_subtitle']));
			$this->fw->content['sound']		= array_map('trim', explode("\n", $this->fw->config['movie_sound']));

		}

		function process_email_list_form()
		{

            $email_addresses	= trim($_POST['email_addresses']);
            $subject            = trim($_POST['subject']);
            $preview			= $_POST['preview'];
            $format				= $_POST['format'];
            $attachment			= $_POST['attachment'] == '1' ? true : false;
            $movie_title		= trim($_POST['movie_title']);
            $genres				= $_POST['genre'];

			$member_id			= $this->sec->dtls['id'];

			// Error Checking

			$errors = array();

			if(empty($email_addresses))
			{

				$errors['email_addresses'] = 'At least one email address must be provided.';

			}

			$emails = explode(';', $email_addresses);
			$emails	= array_map('trim', $emails);

			foreach($emails as $k=>$v)
			{

				if(empty($v)) unset($emails[$k]);

				if(!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $v))
				{

					$errors['email_addresses'] = 'Contains 1 or more invalid email addresses.';

				}

			}

			if(count($emails) < 1 || !is_array($emails))
			{

				$errors['email_addresses'] = 'At least one email address must be provided.';

			}

			if(empty($subject))
			{

				$errors['subject'] = 'A subject must be provided.';

			}

			if(strlen($subject) > 255)
			{

				$errors['subject'] = 'The subject may not exceed 255 characters.';

			}

			if(empty($genres) || !is_array($genres) || count($genres) < 1)
			{

				$errors['genres'] = 'At least 1 genre must be selected.';

			}

			if(count($errors) == 0)
			{

				// Lets get the list of movies we will be sending
				$where = array();

				if(count($genres) != count($this->fw->get_genres()))
				{

					// Not all the genres have been selected
					$where[] = "mg.genre_id IN (". implode(',', $genres) .")";

				}

				if(!empty($movie_title))
				{

					$where[] = "m.movie_title LIKE '%$movie_title%'";

				}

				$where = count($where) == 0 ? null : " AND ". implode(" AND ", $where);

				$sql	= $this->fw->_pq("SELECT m.movie_id, m.movie_title, m.movie_imdb, o.borrowed_by, m.movie_year FROM #__movies m INNER JOIN #__own o ON m.movie_id = o.movie_id INNER JOIN #__lnk_movie_genre mg ON m.movie_id = mg.movie_id WHERE o.member_id = '$member_id' $where GROUP BY m.movie_id ORDER BY m.movie_title ASC");
				$result	= mysql_query($sql) or die(mysql_error());
				//echo $this->fw->_debug_sql();

				$i = 1;
				$attach = null;
				while($row = mysql_fetch_row($result))
				{

					$movies[]	= array('id'		=> $row[0],
										'title'		=> $row[1],
										'year'		=> $row[4],
										'imdb'		=> $row[2],
										'imdb_url'	=> $this->fw->imdb_url($row[2]),
										'borrowed'	=> $row[3]);

					$imdb = str_replace('%%', $row[2], $this->fw->config['imdb_url']);

					if($attachment || $format == 'text')
					{

						$attach .= "$i. {$row[1]} ($imdb)\r\n";

					}
					else
					{

						//$attach .= "$i. <a href=\"$imdb\">{$row[1]}</a><br />";

					}

					$i++;

				}

				//echo '<pre>'. $attach .'</pre>';

				// --= Create new smarty object for template
				$smarty = new Smarty();
				$smarty->template_dir = _BASE_PATH .'/templates/'. $this->fw->config['smarty_template'] .'/';

				$smarty->assign('movies', $movies);
				$smarty->assign('config', $this->fw->config);

				$member_id		= $this->sec->dtls['id'];
				$member_dtls	= $this->fw->get_member_details($member_id);

				$subject		= str_replace('%name%', ucwords($member_dtls['username']), $subject);

				// Lets loop though the emails, and send them out
				foreach($emails as $email)
				{

					$header = "From: Movie Manager <>\n";
					$header .= "To: $email <$email>\n";

					if($format == 'html')
					{

						$header .= "MIME-Version: 1.0\n";
						$header .= "Content-type: text/html; charset=iso-8859-1\n";

						$smarty->assign('to_email', $email);
						//$smarty->assign('list', ($attachment ? null : nl2br($attach .'<br />')));

						$content = $smarty->fetch('mymovies.email.html.tpl');

					}
					else
					{

						$content = $smarty->fetch('mymovies.email.text.tpl');

					}
					//echo $content;
					mail($email, $subject, $content, $header);

				}

			}
			else
			{

				$this->email_list_form('An error has been detected.', $errors);


			}

		}

		function remove_movies()
		{

			// --= Remove selected MOVIE id's from the current members collection!

			$id			= $_REQUEST['id'];
			$id			= is_array($id) ? $id : array($id);

			$member_id	= (int)$this->sec->dtls['id'];

			$i			= 0;

			foreach($id as $v)
			{

				$rem = true;

				if($this->fw->config['allow_remove_borrowed'] == '0')
				{

					// Check if this selected movie has been marked as borrowed
					$sql	= $this->fw->_pq("SELECT COUNT(movie_id) FROM #__borrow WHERE owner_id = %s AND movie_id = %s", $member_id, (int)$v);
					$result	= mysql_query($sql) or die(mysql_error());

					// If movie is currently borrowed then we can't remove this movie from the collection
					if(mysql_result($result, 0, 0) > 0) $rem = false;

				}

				if($rem) // We can remove this selected movie
				{

					// Remove related movies
					$sql	= $this->fw->_pq("DELETE FROM #__own WHERE member_id = %s AND movie_id = %s", $member_id, (int)$v);
					$result	= mysql_query($sql) or die(mysql_error());

					$i		+= mysql_affected_rows();

					// Remove any related borrow entries
					$sql	= $this->fw->_pq("DELETE FROM #__borrow WHERE owner_id = %s AND movie_id = %s", $member_id, (int)$v);
					$result	= mysql_query($sql) or die(mysql_error());

				}

			}
			// get the members movie count!
			$this->fw->update_member_movie_count($member_id);

			$_SESSION['msg']	= $i .' Movie(s) successfully removed from your collection';
			header('location: index.php?what=mymovies');
			exit;

		}

		// Private function
		// Checks all the elements of a 1 dimentional array. If any values are empty, it returns false
		function _check_array($array)
		{


			if(is_array($array))
			{

				foreach($array as $v)
				{

					$v = trim($v);

					if(empty($v))
					{

						return false;

					}

				}

				return true;

			}

			return false;

		}

	}

?>
